package com.uduemc.biso.node.module.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uduemc.biso.node.core.entities.HRobots;
import com.uduemc.biso.node.module.mapper.HRobotsMapper;
import com.uduemc.biso.node.module.service.HRobotsService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class HRobotsServiceImpl implements HRobotsService {

	@Autowired
	private HRobotsMapper hRobotsMapper;

	@Override
	public HRobots insertAndUpdateCreateAt(HRobots hRobots) {
		hRobotsMapper.insert(hRobots);
		HRobots findOne = findOne(hRobots.getId());
		Date createAt = hRobots.getCreateAt();
		if (createAt != null) {
			hRobotsMapper.updateCreateAt(findOne.getId(), createAt, HRobots.class);
		}
		return findOne;
	}
	
	@Override
	public HRobots insert(HRobots hRobots) {
		hRobotsMapper.insert(hRobots);
		return findOne(hRobots.getId());
	}

	@Override
	public HRobots updateById(HRobots hRobots) {
		hRobotsMapper.updateByPrimaryKeySelective(hRobots);
		return findOne(hRobots.getId());
	}

	@Override
	public HRobots updateAllById(HRobots hRobots) {
		hRobotsMapper.updateByPrimaryKey(hRobots);
		return findOne(hRobots.getId());
	}

	@Override
	public HRobots findOne(long id) {
		return hRobotsMapper.selectByPrimaryKey(id);
	}

	@Override
	public void deleteById(long id) {
		hRobotsMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int deleteByHostId(long hostId) {
		Example example = new Example(HRobots.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		return hRobotsMapper.deleteByExample(example);
	}

	@Override
	public HRobots findOneNotOrCreate(long hostId) {
		Example example = new Example(HRobots.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		example.setOrderByClause("`id` ASC");
		List<HRobots> selectByExample = hRobotsMapper.selectByExample(example);
		if (selectByExample.size() == 0) {
			// 创建
			HRobots data = new HRobots();
			data.setHostId(hostId).setStatus((short) 0).setRobots("");
			return insert(data);
		} else if (selectByExample.size() == 1) {
			return selectByExample.get(0);
		} else {
			for (int i = 1; i < selectByExample.size(); i++) {
				deleteById(selectByExample.get(i).getId());
			}
			return selectByExample.get(0);
		}
	}

	@Override
	public Integer queryWebsiteRobotsCount(int trial, int review) {
		return hRobotsMapper.queryWebsiteRobotsCount(trial, review);
	}

}
